package cn.itcast.bos.web.action.system;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.domain.utils.BaseAction;
import cn.itcast.bos.service.system.MenuService;

@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class MenuAction extends BaseAction<Menu> {

	@Autowired
	private MenuService menuService;

	@Action(value = "menu_list", results = { @Result(name = "success", type = "json") })
	public String menu_list() {

		List<Menu> menus = menuService.findAll();
		ServletActionContext.getContext().getValueStack().push(menus);

		return SUCCESS;
	}

	@Action(value = "menu_findparentAll", results = { @Result(name = "success", type = "json") })
	public String menu_findparentAll() {

		List<Menu> menus = menuService.findByparentMenu();
		for (Menu menu : menus) {
			System.out.println(menu.toString());
		}
		ServletActionContext.getContext().getValueStack().push(menus);
		return SUCCESS;
	}

	@Action(value = "menu_save", results = {
			@Result(name = "success", type = "redirect", location = "/pages/system/menu.html") })
	public String menu_save() {
		System.out.println(model.getParentMenu());
		System.out.println(model.getParentMenu().getId());
		if (model.getParentMenu() != null && model.getParentMenu().getId() == 0) {
			model.setParentMenu(null);
		}
		menuService.save(model);

		return SUCCESS;
	}

	@Action(value = "menu_findByUser", results = { @Result(name = "success", type = "json") })
	public String menu_findByUser() {
		// 获得当前登录用户
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		List<Menu> menus = null;
		if (user.getUsername().equals("admin")) {
			menus = menuService.findAll();
		} else {
			// 调用业务成方法查询当前用户所拥有的菜单权限
			menus = menuService.findByUser(user);
		}
		ServletActionContext.getContext().getValueStack().push(menus);

		return SUCCESS;
	}

}
